// pages/editClass/editClass.js
var request = require('../../operation/operation.js')
var gradeModel = require('../../models/grade.js')
var klassModel = require('../../models/klass.js')
let schoolModel = require('../../models/school.js')
let bxt = require('../../utils/bxt.js')
let category = schoolModel.CATEGORY_PRIMARY_SCHOOL
let klass = null, mode = 'create'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // region: null,
    category: category,  // 学校类别
    enrolYear:'',
    enrolYearWithGrade: '',
    classes:klassModel.CLASSES,
    classIndex:0,
    klass:{}
    // school:null
  },

  /**
   * 生命周期函数--监听页面加载
   * options: category 上个界面传来的学校类别
   */
  onLoad: function (options) {
    this.initDatePicker()

    if (options.category) {
      this.initCategory(options.category)        
    }

    if (options.edit) {
      mode = 'edit'
      klass = getApp().globalData.param
      this.initCategory(klass.category)      
      this.initKlass()
      wx.setNavigationBarTitle({
        title: '编辑班级',
      })
    }else {
      mode = 'create'
      wx.setNavigationBarTitle({
        title: '添加班级',        
      })
    }
    // getApp().notificationCenter.register(bxt.EDIT_SCHOOL_MESSAGE, this, "handleSelectSchoolMessage");
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    klass = null
    // getApp().notificationCenter.remove(bxt.EDIT_SCHOOL_MESSAGE, this)
  },

  /**
   * 点击选择学校事件处理函数
   */
  onShowSchoolList:function () {
    if(null == this.data.region) {
      wx.showModal({
        title: '提示',
        content: "请先选择地区",
        showCancel: false
      })
    }else {
      getApp().globalData.param = this.data.region

      wx.navigateTo({
        url: '../schoolList/schoolList',
      })
    }
  },

  /**
   * 单击确定按钮事件的处理函数
   */
  next:function(event) {    
    let message = null,klassName = '',schoolName = '';
    if ('' == event.detail.value.schoolName.trim()) {
      message = "请填写学校名字"
    }else {
      schoolName = event.detail.value.schoolName.trim()
    }
    if (schoolModel.CATEGORY_TRAINING_SCHOOL == category) {
      if ('' == event.detail.value.klassName.trim()) {
        message = "请填写班级名字"
      }else {
        klassName = event.detail.value.klassName.trim()
      }    
    }
    // if (null == this.data.region) {
    //   message = "请选择地区";
    // }else if (null == this.data.school) {
    //   message = "请选择学校";
    // }

    if (null != message) {
      wx.showModal({
        title: '提示',
        content: message,
        showCancel:false
      })
    }else {
      getApp().createFormId(event.detail.formId)
      // 将值设置到全局参数中，供下级界面使用
      // getApp().globalData.param = { "region": this.data.region, "school": this.data.school, "enrolDate": this.data.enrolYear, "class": this.data.classIndex}
      if (mode == 'create') {
        getApp().globalData.param = { "category": category, "schoolName": schoolName, "klassName": klassName, "enrolDate": this.data.enrolYear, "class": this.data.classIndex }     
        wx.navigateTo({
          url: '../bindMobile/bindMobile',
        })
      }else if (mode == 'edit') {
        let params = { 'schoolName': schoolName}        
        if (schoolModel.CATEGORY_PRIMARY_SCHOOL == klass.category) {
          params.enrollDate = this.data.enrolYear + '-09-01'
          params.index = parseInt(this.data.classIndex) + 1          
        }else {          
          params.name = klassName
        }

        this.updateKlass(params)
      }
    }
  },

  /**
   * 地区确定按钮事件处理函数
   */
  bindRegionChange:function(event) {
    this.setData({
      region: event.detail.value
    })
  },

  /**
   * 年级确定按钮事件处理函数
   */
  bindGradeChange:function(event) {    
    /*
     * 根据用户选择的年份，合成 "年份 - 二年级" 样式的文字
     */
    let value = new String(event.detail.value)
    let parts = value.split('　')
    let year = parts[0]

    this.setData({
      enrolYear: year,
      enrolYearWithGrade: yearWithGrade(year)
    })
  },

  /**
   * 班级确定按钮事件处理函数
   */
  bindClassChange:function(event) {
    this.setData({
      classIndex: event.detail.value
    })
  },

  updateKlass:function(params) {
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    var that = this
    request.putRequest('/klasses/' + klass.sid, params, true)
      .then(res => {
        wx.hideLoading()
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          getApp().notificationCenter.post(bxt.UPDATE_KLASS_MESSAGE)
          
          getApp().autoBack('编辑成功')
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }

      }).catch(e => {
        wx.hideLoading()
      })
  },

  handleSelectSchoolMessage: function (object) {
    this.setData({
      school:object.school
    })
  },

  initDatePicker:function() {
    var date = new Date()
    var year = date.getFullYear()
    var month = date.getMonth()

    if (month < 9) {
      // 设定每年 9 月是入学年份，当前年份小于 9 月，说明一定至少是去年入学
      year = year - 1
    }

    this.setData({
      enrolYear:year,
      startYear:year - 5,
      endYear:year,
      enrolYearWithGrade: yearWithGrade(year)
    })
  },

  initCategory:function(tmpCategoty) {
    category = tmpCategoty 
    this.setData({
      category: category
    })
  },

  initKlass:function() {
    this.setData({
      klass: klass,
      classIndex: klass.index - 1,
    })

    if (klass.enrollDate) {
      let year = parseInt(klass.enrollDate.split('-')[0])      
      this.setData({ 
        enrolYear: year.toString(), 
        enrolYearWithGrade: yearWithGrade(year)
      })
    }
  }
});

function yearWithGrade(year) {
  let grade = gradeModel.getGradeByEnrolDate(year)
  // 下面的空格是"全角空格"，否则只能显示一个空格
  return year + "　　" + grade.name
}